package com.xmutca.sso.provider.manager;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.xmutca.core.common.Paging;
import com.xmutca.core.common.Receipt;
import com.xmutca.core.common.Result;
import com.xmutca.core.common.Results;
import com.xmutca.sso.api.Account;
import com.xmutca.sso.api.manager.service.AccountService;
import com.xmutca.sso.dao.AccountDao;
import com.xmutca.sso.dao.UserPermissionDao;
import com.xmutca.sso.dao.UserRoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-23 22:12
 */
@Service(version = "1.0.0", group = "sso", mock = "true")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private UserPermissionDao userPermissionDao;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public Result<Account> get(String id) {
        return new Result<>(Result.Status.SUCCESS, accountDao.getById(id));
    }

    @Override
    @Transactional
    public Receipt assignPermission(String id, List<Integer> permissions) {
        if (CollectionUtils.isNotEmpty(permissions)) {
            for (Integer permission:permissions) {
                userPermissionDao.add(id, permission);
            }
        }
        return new Receipt(Result.Status.SUCCESS);
    }

    @Override
    @Transactional
    public Receipt assignRole(String id, List<Integer> roles) {
        if (CollectionUtils.isNotEmpty(roles)) {
            for (Integer role:roles) {
                userRoleDao.add(id, role);
            }
        }
        return new Receipt(Result.Status.SUCCESS);
    }

    @Override
    public Receipt recoveryPermission(String id, List<Integer> permissions) {
        if (CollectionUtils.isNotEmpty(permissions)) {
            userPermissionDao.delByUserPermissions(id, permissions);
        }
        return new Receipt(Result.Status.SUCCESS);
    }

    @Override
    public Receipt recoveryRole(String id, List<Integer> roles) {
        if (CollectionUtils.isNotEmpty(roles)) {
            userRoleDao.delByUserRoles(id, roles);
        }
        return new Receipt(Result.Status.SUCCESS);
    }

    @Override
    public Results<Account> query(int current, int pageSize, Map<String, Object> paramMap) {
        int count = accountDao.countQuery(paramMap);
        paramMap.put("startRow", (current - 1) * pageSize);
        paramMap.put("pageSize", pageSize);
        List<Account> accounts = accountDao.query(paramMap);
        return new Results<>(Results.Status.SUCCESS, accounts, new Paging(current, pageSize, count));
    }
}